<template>
  <div class="providers">
    <div class="providersList">
      <span class="title">{{$t('task.detail.components.settlementDoc')}}：</span>
      <span class="provide-content link" @click="gotoSettleDetail(settleDetail.id)">{{ settleDetail.settleNo }}</span>
    </div>
    <div class="providersList">
      <span class="title">{{$t('task.detail.components.settlementState')}}：</span>
      <span
        class="state"
        :style="{background: settleStatus}"
      >{{ stateName }}</span
      >
    </div>
    <div class="providersList">
      <span class="title">{{$t('task.list.displayName.balanceTime')}}：</span>
      <span class="provide-content">{{ settleDetail.settleTime}}</span>
    </div>
    <div class="providersList">
      <span class="title">{{$t('task.detail.components.settlementDesc')}}：</span>
      <span class="provide-content">{{ settleDetail.comment }}</span>
    </div>
    <div class="providersList">
        <el-table
          :data="tableData"
          border
          style="width: 100%">
            <el-table-column type="index" width="50" :label="$t('common.base.SN')" />
            <el-table-column
              prop="name"
              :label="$t('task.detail.components.settlementProject')">
              <template slot-scope="scope">
                <template v-if="isEdit">
                  <el-input maxlength="50" v-model="tableOldData[scope.$index].name" />
                </template>
                <div v-else>{{ scope.row.name }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="comment"
              :label="$t('task.detail.components.projectDesc')">
              <template slot-scope="scope">
                <template v-if="isEdit">
                  <el-input  maxlength="100" v-model="tableOldData[scope.$index].comment" />
                </template>
                <div v-else>{{ scope.row.comment }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="amount"
              :label="$t('task.detail.components.money')">
              <template slot-scope="scope">
                <template v-if="isEdit">
                  <el-input type="number" v-model="tableOldData[scope.$index].amount" @change="(value)=>SaveAmount(value,scope.$index)" />
                </template>
                <div v-else>{{ scope.row.amount }}</div>
              </template>
            </el-table-column>
             <el-table-column
              prop="remark"
              :label="$t('common.base.remark')">
              <template slot-scope="scope">
                <template v-if="isEdit">
                  <el-input  maxlength="100" v-model="tableOldData[scope.$index].remark" />
                </template>
                <div v-else>{{ scope.row.remark }}</div>
              </template>
            </el-table-column>
            <el-table-column
              v-if="isEdit"
              :label="$t('common.base.edit')">
                <template slot-scope="scope">
              <el-button
                @click="Delete(scope)"
                type="text"
                style="color:#f44552"
              >
                {{$t('common.base.delete')}}
              </el-button>
               </template>
            </el-table-column>
        </el-table>

      <!-- 底部数据量统计 -->
      <div class="table-footer">
        <i18n path="common.base.table.totalCount">
          <span place="count" class="level-padding">{{tableAllData.length || 0}}</span>
        </i18n>
      </div>
    </div>
     <div v-if="isEdit" class="providersList" style="justify-content: flex-end;">
       <span class="Add" @click="add"><i class="el-icon-plus"></i>{{$t('task.detail.components.addProject')}}</span>
     </div>
    <div class="providersList" style="justify-content: flex-end;">
      <span class="title">{{$t('task.detail.components.totalAmount')}}：</span>
      <span class="provide-content" style="color:#f59a83;">
        <template v-if="isEdit">
           {{ account1 }}
        </template>
         <template v-else>
           {{ account }}
        </template>
      </span>
    </div>
    <!--未结算并且拥有服务商结算的权限才能进行结算-->
    <div class="providersText" >
      <!-- TODO 国际化待办 -->
      <template v-if="provideSettleConfig && provideSettleConfig.btnVisible && stateName === '未结算' && !isEdit">
      <button @click="isEdit = false;OpenSettlement()" type="button" class="add">
        <span class="iconfont icon-add2"></span>
        <div>{{$t('task.detail.components.addToSettlement')}}</div>
      </button>
      <button
        :disabled="isClick"
        @click="serviceSettle"
        type="button"
        class="btn btn-primary base-comment-submit"
      >
        {{$t('task.providerSettle')}}
      </button>
      </template>
      <!-- TODO 国际化待办 -->
      <template v-if="provideSettleConfig && provideSettleConfig.itemBtnVisible && ['未结算','结算中'].includes(stateName)">
       <button
        v-if="!isEdit"
        @click="isEdit = true"
        type="button"
        style="margin-left:8px"
        class="btn btn-primary base-comment-submit"
      >
        {{$t('common.base.edit')}}
      </button>
      <template  v-else>
      <el-button
        :loading="SaveLoading"
        @click="Save"
        type="button"
        style="margin-left:8px"
        class="btn btn-primary base-comment-submit"
      >
        {{$t('common.base.save')}}
      </el-button>
      <el-button
        @click="cancel"
        type="button"
        style="margin-left:8px"
        class="btn btn-primary base-comment-submit"
      >
        {{$t('common.base.cancel')}}
      </el-button>
      </template>
     
      </template>
    </div>
    <AddSettlement :is-settlement="isSettlement" :task-id="task.id" :provider-id="providerId" @Close="isSettlement = false" @refresh-settle="refreshPage"/>
    <base-modal
      :show.sync="settleVisible"
      :title="$t('task.providerSettle')"
      class="settle-choose-dialog"
      width="480px"
    >
      <div>
        <label>{{$t('common.form.type.serviceProviders')}}</label>
        <el-select
          v-model="providerChoose"
          :placeholder="$t('common.placeholder.select')"
        >
          <el-option
            v-for="item in providersModule"
            :key="item.id"
            :label="item.tagName"
            :value="item.id">
          </el-option>
        </el-select>
      </div>
      <div slot="footer">
        <el-button @click="settleVisible = false">{{$t('common.base.close')}}</el-button>
        <el-button type="primary" @click="saveSettle" :loading="settleLoading">{{$t('common.task.button.balance')}}</el-button>
      </div>
    </base-modal>
  </div>
</template>

<script>
/* api */
import * as TaskApi from '@src/api/TaskApi.ts';
import { ref } from 'vue';
import AddSettlement from './AddSettlement';
import { formatDate } from 'pub-bbx-utils';
import { safeNewDate } from '@src/util/time';
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
export default {
  name: 'settlement-providers',
  components: {
    AddSettlement,
  },
  props: {
    task: {
      type: Object,
      default: () => ({})
    },
    provideSettleConfig: {
      type: Object,
      default: () => ({})
    },
  },
  data() {
    return {
      settleVisible: false,
      providersModule: [],
      providerChoose: '',
      isClick: false,
      settleDetail: {},
      stateName: '',
      settleLoading: false,
      account: 0,
      providerId: '',
      // 结算
      tableData:[],
      tableOldData:[],
      isEdit:false,
      SaveLoading:false
    }
  },
  setup(props, context) {


    // 添加至已有结算单
    let isSettlement = ref(false);
    function OpenSettlement() {
      isSettlement.value = !isSettlement.value;
    }

    return { OpenSettlement, isSettlement };
  },
  methods: {
    Delete(scope){
      this.tableData.splice(scope.$index,1)
      this.tableOldData = this.tableData
    },
    add(){
      this.tableData.push({
        name:'',
        comment:'',
        amount:"",
        remark:'',
        sumed:0
      })
      this.tableOldData = this.tableData
    },
    Save(){
      let sum = 0
      for(let item of  this.tableOldData){
        if(!item.name){
          this.$message.warning(this.$t('task.tip.settlementTip4'))
          return
        }
        if(!item.amount){
          this.$message.warning(this.$t('task.tip.settlementTip5', {name: item.name}))
          return
        }
        if(!item.amount > 9999999.99){
          this.$message.warning(this.$t('task.tip.settlementTip6', {name: item.name}))
          return
        }
        sum += item.amount
      }
      if(sum > 100000000){
        this.$message.warning(this.$t('task.tip.settlementTip7'))
        return
      }
      this.SaveLoading = true
      TaskApi.TaskSaveTaskItem({
        items: this.tableOldData,
        taskId: this.task?.id,
        taskNo:this.task?.taskNo,
        settleId:this.settleDetail.id
      })
      .then(res=>{
        this.SaveLoading = false
        if(res.code === 0){
          this.$message.success(res.message)
          this.isEdit = false
          this.$emit('refresh-page')
        }else{
          this.$message.error(res.message)
        }
      })
    },
    TaskGetTaskItem(){
      TaskApi.TaskGetTaskItem({
        taskId: this.task?.id
      })
      .then(res=>{
        if(res.code === 0){
          this.tableData = res.result
          this.tableOldData = JSON.parse(JSON.stringify(this.tableData))
        }
      })
    },
    refreshPage() {
      this.$emit('refresh-page')
    },
    async initializeSettle() {
      try {
        let data = {
          taskId: this.task?.id,
        }
        let res = await TaskApi.getTaskSettleInfo(data);
        if(res.success && res.code === 0) {
          this.settleDetail = res.result?.settle || '';
          this.stateName = res.result?.stateName;
          if(this.settleDetail && this.settleDetail.settleTime) {
            this.settleDetail.settleTime = this.settleDetail.settleTime && formatDate(safeNewDate(parseInt(this.settleDetail.settleTime)), 'yyyy-MM-dd HH:mm:ss')
          }
          this.account = res.result?.account;
          this.providerId = res.result?.providerId;
        }
      }catch (error) {
        console.error('initialize settle error', error)
      }
      this.TaskGetTaskItem()
    },
    /* 查看结算单详情*/
    gotoSettleDetail(id) {
      if(id) {
        openAccurateTab({
          type: PageRoutesTypeEnum.PagePcResourceManage,
          key: id,
          params: `id=${id}`
        })
      }
    },
    // 服务商结算
    async serviceSettle() {
      try {
        this.isEdit = false
        this.isClick = true;
        let data = {
          objectIds: [this.task?.id],
          type: 1,
        }
        let res = await TaskApi.checkSettle(data)
        if(res.code === 0) {
          if('-1' in res.result) {
            this.$message({
              type: 'error',
              message: this.$t('task.tip.settlementTip8'),
            });
          }else if('1' in res.result) {
            // 情况一，只有一个相同的服务商，直接调用接口
            let data = {
              providerId: res.result[1], // 服务商id
              taskIds: [this.task?.id], // 工单集合
              type: 1,
            }
            let settleRes = await TaskApi.createSettle(data);
            this.$platform.notification({
              type: settleRes.success ? 'success' : 'error',
              message: settleRes.success ? this.$t('task.tip.settlementTip9') : settleRes.message,
            });
            if(settleRes.code === 0) {
              this.refreshPage();
              this.gotoSettleDetail( settleRes.result.length ? settleRes.result[0] : ''); // 跳转到结算单详情也
            }
          }/*else if ('1' in res.result) {
            // 情况二，弹窗选择服务商，后调用接口
            this.settleVisible = true;
            this.providersModule = res.result[1];
          }*/
        }
      } catch (error) {
        console.error('service settle error', error);
      } finally {
        this.isClick = false;
      }
    },
    async saveSettle() {
      try {
        this.settleLoading = true;
        if(!this.providerChoose.length) {
          this.$message({
            message: this.$t('common.placeholder.selectSomething', {0: $t('common.form.type.serviceProviders')}),
            type: 'warning',
          })
        }
        let data = {
          providerId: [this.providerChoose], // 服务商id
          taskIds: [this.task?.id], // 工单集合
        }
        let res = await TaskApi.createSettle(data);
        this.$platform.notification({
          type: res.code === 0 ? 'success' : 'error',
          title: res.code === 0 ? this.$t('task.tip.settlementTip9') : res.result,
        });
        if(res.code === 0) {
          this.refreshPage();
          this.gotoSettleDetail( res.result.length ? res.result[0] : ''); // 跳转到结算单详情也
        }
      } catch (error) {
        console.error('create settle error', error);
      } finally {
        this.settleVisible = false;
        this.settleLoading = false;
      }
    },
    cancel(){
      this.isEdit = false
      this.tableOldData = JSON.parse(JSON.stringify(this.tableData))
    },
    SaveAmount(value,index){
      if(value){
        this.tableOldData[index].amount = Math.floor(value*100)/100
      }
      if(value < 0){
        this.tableOldData[index].amount = 0
      }
       if(value > 9999999.99){
        this.tableOldData[index].amount =  9999999.99
      }
    }
  },
  mounted() {
    this.initializeSettle();
  },
  computed:{
    settleStatus() {
      // TODO 国际化待办
      if (this.stateName == '未结算') return '#FF7043'
      if (this.stateName == '结算中') return '#1565C0'
      if (this.stateName == '已结算') return '#C0CA33'
      if (this.stateName == '审批中') return '#C0CA33'
    },
    account1(){
      let number = this.tableOldData.reduce((pre,cur)=>{
        return pre + Number(cur.amount)
      },0)
      return Math.floor(number * 100) / 100
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-table{
  border: 1px solid #ebeef5;
}
::v-deep .el-dialog__headerbtn {
  top: 0;
}
.providers {
  padding: 17px 18px;
  width: 100%;
  height: 100%;
  .providersTable {
    width: 100%;
    margin-top: 12px;
  }
  .providersList {
    display: flex;
    align-items: center;
    /*height: 20px;*/
    padding: 6px 0;
    box-sizing: content-box;
    .title {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      min-width: 98px;
      display: flex;
      align-items: center;
      font-weight: 400;
      line-height: 20px;
      flex-shrink: 0;
      margin: 0 10px 0 0;
      color: #595959;
      word-break: break-all;
    }
    .provide-content {
      line-height: 20px;
      overflow-x: hidden;
      color: #262626;
      word-break: break-word;
    }
    .link {
      color: #13c2c1;
      display: flex;
      align-items: center;
      cursor: pointer;
    }
    .state {
      height: 22px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 11px;
      color: #ffffff;
      padding: 3px 8px;
      font-size: 12px;
    }
  }
  .providersText {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-top: 10px;
    .providersCount {
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #262626;
    }
    .providersOperation {
      height: 100%;
      display: flex;
    }
  }
}
.add {
  background: #f5f8fa;
  border: 1px solid #cbd6e2;
  font-size: 14px;
  color: #595959;
  display: flex;
  height: 32px;
  align-items: center;
  margin-right: 12px;
  border-radius: 4px;
  div {
    margin-left: 6px;
    line-height: 20px;
  }
}
::v-deep .el-table__body .el-table__row td .cell, .el-table__header thead tr th .cell{
  line-height: 20px;
  height: auto;
}
</style>
